package com.imooc.bilibili.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * ProjectName imooc-bilibili
 *
 * @author xieyucan
 * <br>CreateDate 2022/10/21 16:49
 */
public class MD5Util {

    /**
     * 加密
     * @param content
     * @param salt
     * @param charset
     * @return
     */
    public static String sing(String content,String salt,String charset)
    {
        content=content+salt;
        return DigestUtils.md5Hex(getContentBytes(content, charset));
    }

    /**
     * 校验是否与原本一样
     * @param content
     * @param sign
     * @param salt
     * @param charset
     * @return
     */
    public static boolean verify(String content,String sign,String salt,String charset)
    {
        content=content+salt;
        String muSign = DigestUtils.md5Hex(getContentBytes(content, charset));
        return muSign.equals(sign);
    }

    private static byte[] getContentBytes(String content,String charset)
    {
        if(!"".equals(charset))
        {
            try {
                return content.getBytes(charset);
            }catch (UnsupportedEncodingException e){
                throw new RuntimeException("MD5签名过程中出现错误，指定的编码集错误");
            }
        }else {
            return content.getBytes();
        }
    }


    /**
     * 获取文件加密之后的md5
     * 这里使用与文件是否已经上传过
     * @param file
     * @return
     */
    public static String getFileMD5(MultipartFile file) throws IOException {
//        InputStream inputStream = file.getInputStream();
//        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//        byte []buffer=new byte[1024];
//        int byteRead;
//        while((byteRead=inputStream.read(buffer))>0)
//        {
//            outputStream.write(buffer,0,byteRead);
//        }
//        inputStream.close();
//        return DigestUtils.md5Hex(outputStream.toByteArray());
        InputStream inputStream = file.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte []bytes=new byte[1024];
        int len;
        while ((len=inputStream.read(bytes))>0)
        {
            byteArrayOutputStream.write(bytes,0,len);
        }
        inputStream.close();
        return DigestUtils.md5Hex(byteArrayOutputStream.toByteArray());
    }
}
